<?php
namespace Admin\Controller;
use Lib\Controller\AdminBaseController;
use Think\Upload;

class AuditController extends AdminBaseController{

    private $serverModel;
    private $serverAddressModel;
    private $serverNameModel;
    private $serverPriceModel;
    private $serverAdminModel;
    private $monthcardModel;
    public function __construct(){
        $this->serverModel = D('Server');
        $this->serverAddressModel = D('serverAddress');
        $this->serverNameModel = D('serverName');
        $this->serverPriceModel = D('serverPrice');
        $this->serverAdminModel = D('serverAdmin');
        $this->monthcardModel   = D('monthCard');
        parent::__construct();
    }

    /**
     * [month_card_list 月卡列表]
     * @author xiezy
     * @date   2017-11-24
     * @return [type]     [description]
     */
    public function month_card_list(){
        //服務列表
        $serverNameWhere['server_type'] = array('in',array('2','3')); // 单次和通用服务
        $serverNameList = $this->serverNameModel->where($serverNameWhere)->select();
        //月卡列表
        $where['server_id'] = -1;
        $monthcardList = $this->monthcardModel->where($where)->select();
        if (!empty($monthcardList)) {
            foreach ($monthcardList as $key => $value) {
                $monthcardList[$key]['server_name_list'] = unserialize($value['server_name_list']);
            }
        }

        $this->assign('server',$serverNameList);
        $this->assign('list',$monthcardList);
        $this->display();
    }

    /**
     * [add_month_card 添加月卡 服务内容（使用次数）]
     * @author xiezy
     * @date   2017-11-27
     */
    public function add_month_card(){
        $serverNameArr = array();
        if ( !empty(I('post.server_name_list',0)) ) {
            $serverJson = trim(I('post.server_name_list'),',');
            $serverJson = explode(',', $serverJson);

            if (!empty($serverJson['0']) ) {
                foreach ($serverJson as $key => $value) {
                    $ret = explode('|', $value);
                    $serverNameArr[] = array('id'=>$ret['0'],'server_name'=>$ret['1'],'server_times'=>$ret['2']);
                }
            }else{
                $serverNameArr = '';
            }
        }else{
            $msg['status'] = 0;
            $msg['info'] = '服務內容不能爲空!';
            $this->ajaxReturn($msg);
        }
        // echo '<meta charset="UTF-8"><pre>xie '.date('Y-m-d H:i:s',time()).'</br></br>';var_dump($serverNameArr);die;
        $spData['server_name_list'] = serialize( $serverNameArr );
        $spData['month_card_name']  = I('post.month_card_name');//月卡名
        $spData['month_card_total'] = I('post.month_card_total');//月卡 价格
        $spData['server_id']        = -1;
        $spData['create_time']      = time();
        $spData['status']           = 1;
        $addNewCard = $this->monthcardModel->add($spData);
        if($addNewCard){
            $info['status'] = 1;
            $info['info'] = '添加成功';
            $info['url'] = U(MODULE_NAME.'/Audit/month_card_list');
            $this->ajaxReturn($info);
        }else{
            $info['status'] = 0;
            $info['info'] = '添加失敗';
            $this->ajaxReturn($info);
        }
    }

    /**
     * [change_month_status 修改月卡状态]
     * @author xiezy
     * @date   2017-12-02
     * @return [type]     [description]
     */
    public function change_month_status(){
        $where['id'] = I('get.id');
        $result = $this->monthcardModel->where($where)->find();

        $status = $result['status'] > 0 ? 0 : 1;
        $updateServerName = $this->monthcardModel->where($where)->save(array('status'=>$status,'update_time'=>time()));

        if($updateServerName){
            $info['status'] = 1;
            $info['info'] = '修改成功';
            $info['url'] = U(MODULE_NAME.'/Audit/month_card_list');
            $this->ajaxReturn($info);
        }else{
            $info['status'] = 0;
            $info['info'] = '修改失敗';
            $this->ajaxReturn($info);
        }
    }

    /**
     * [delete_month_list 删除月卡]
     * @author xiezy
     * @date   2017-12-02
     * @return [type]     [description]
     */
    public function delete_month_list() {
        $where['id'] = I('get.id');

        $deleteMonth = $this->monthcardModel->where($where)->delete();
        if($deleteMonth){
            $info['status'] = 1;
            $info['info'] = '刪除成功';
            $info['url'] = U(MODULE_NAME.'/Audit/month_card_list');
            $this->ajaxReturn($info);
        }else{
            $info['status'] = 0;
            $info['info'] = '刪除失敗';
            $this->ajaxReturn($info);
        }
    }

    /**
     * 洗車點列表
     */
    public function address_list(){
        $where['server_id'] = -1;
        $serverAddressList = $this->serverAddressModel->where($where)->select();
        $this->assign('list',$serverAddressList);
        $this->display();
    }
    /**
     * 洗車點詳情
     */
    public function edit_address(){
        if(IS_GET){
            $where['id'] = $priceWhere['server_address_id'] = I('get.id');
            //洗車點信息
            $addressInfo = $this->serverAddressModel->where($where)->find();
            //洗車點對應服務信息
            $addressServerPrice = $this->serverPriceModel->where($priceWhere)->select();
            //服務列表
            $serverNameWhere['server_type'] = array('in',array('1','3')); // 单次和通用服务
            $serverNameList = $this->serverNameModel->where($serverNameWhere)->select();

            foreach($serverNameList as $snl =>$s){
                $serverNameList[$snl]['check'] = 0;
                foreach($addressServerPrice as $k =>$v){
                    if($s['id'] == $v['server_name_id']){
                        $serverNameList[$snl]['check'] = 1;
                        $serverNameList[$snl]['price'] = $addressServerPrice[$k];
                        break;
                    }
                }
            }

            $this->assign('list',$serverNameList);
            $this->assign('info',$addressInfo);
            $this->assign('price',$addressServerPrice);
            $this->assign('type',$_GET['type']);
            $this->display();
        }
    }
    /**
     * 添加新的服务项目
     */
    public function add_address(){
        if(IS_GET){
            //服務列表
            $serverNameWhere['server_type'] = array('in',array('1','3')); // 单次和通用服务
            $serverNameList = $this->serverNameModel->where($serverNameWhere)->select();
            $this->assign('list',$serverNameList);
            $this->assign('type','add');
            $this->display('edit_address');
        }
        if(IS_POST){
            if(I('post.action')=='edit'){
                $serverAddressWhere['id'] = I('post.server_id');
                $serverAddressInfo = $this->serverAddressModel->where($serverAddressWhere)->find();
            }
            //洗車點保存信息
            $data['server_id'] = -1;
            $data['address_name'] = I('post.name');
            $data['location'] = I('post.location');
            $analysisData['address'] = I('post.location');
            $analysisResult = $this->address_analysis($analysisData);
            $analysis = explode(',', $analysisResult['geocodes'][0]['location']);

            $data['lon'] = $analysis[0];
            $data['lat'] = $analysis[1];

            $data['server_start_time'] = I('post.start_time');
            $data['server_end_time'] = I('post.end_time');
            $data['time_interval'] = I('post.time_interval');
            $data['meanwhile_order'] = I('post.meanwhile_order');
            $data['create_time'] = time();
            $data['address_phone'] = I('post.address_phone');
            $data['tips'] = I('post.tips');
            $data['status'] = I('post.status');
            //判斷是否有上傳圖片
            if($_FILES['upload_shopImg']['name']){
                $config = array(
                    'maxSize' => 0, //上传的文件大小限制 (0-不做限制)
                    'exts' => array('jpg', 'gif', 'png', 'jpeg'),// 设置附件上传类型
                    'subName' => array('date', 'Ymd'), //子目录创建方式，[0]-函数名，[1]-参数，多个参数使用数组
                    'saveName'   =>    array('uniqid',''),
                    'savePath' => 'server_img/', //保存路径
                    'rootPath' => './Upload/',
                    'autoSub'    =>    true,
                );
                $this->uploader = new Upload($config, 'Local');
                $info = $this->uploader->upload($_FILES);
                if(!$info){//提示错误信息
                    $returndata ['status'] = 0; // 状态
                    $returndata ['info'] = $this->uploader->getError();
                    $this->ajaxReturn($returndata);
                }else{
                    foreach($info as$x =>$val){
                        $data['address_img'] = '/upload/'.$val['savepath'] . $val['savename'];
                    }
                }
            }
            if(I('post.action')=='edit'){
                @unlink($serverAddressInfo['address_img']);
                $addNewAddress = $this->serverAddressModel->where($serverAddressWhere)->save($data);
                //獲取新洗車點的id
                $newAddressId = $serverAddressInfo['id'];
                //删除原有价格数据
                $deleteWhere['server_address_id'] = $newAddressId;
                $this->serverPriceModel->where($deleteWhere)->delete();
            }else{
                $addNewAddress = $this->serverAddressModel->add($data);
                //獲取新洗車點的id
                $newAddressId = $addNewAddress;
            }


            $serverNameId = I('post.server_name_id');
            $serverNameIdList = array_filter(explode(',', $serverNameId));
            //獲取服務的價格對應洗車點id進行保存
            foreach($serverNameIdList as $key=>$val){
                $spData['server_address_id'] = $newAddressId;
                $spData['server_name_id'] = $val;
                $spData['five_price'] = I('post.five_sn_price_'.$val);
                $spData['seven_price'] = I('post.seven_sn_price_'.$val);
                $spData['other_price'] = I('post.other_sn_price_'.$val);
                $this->serverPriceModel->add($spData);
            }
            if($addNewAddress){
                $info['status'] = 1;
                $info['info'] = '添加成功';
                $info['url'] = U(MODULE_NAME.'/Audit/address_list');
                $this->ajaxReturn($info);
            }else{
                $info['status'] = 0;
                $info['info'] = '添加失敗';
                $this->ajaxReturn($info);
            }
        }
    }

    /**
     * 刪除服務
     */
    public function delete_address_list() {
        $where['id'] = I('get.id');

        $deleteServer = $this->serverAddressModel->where($where)->delete();
        if($deleteServer){
            $info['status'] = 1;
            $info['info'] = '刪除成功';
            $info['url'] = U(MODULE_NAME.'/Audit/address_list');
            $this->ajaxReturn($info);
        }else{
            $info['status'] = 0;
            $info['info'] = '刪除失敗';
            $this->ajaxReturn($info);
        }
    }

    /**
     * 店長審核列表
     */
    public function audit_list(){
        $where['is_shopowner'] = -1;

        $result = $this->serverModel->where($where)->select();

        $this->assign('list',$result);

        $this->display();
    }
    /**
     * 修改店長審核狀態
     * 通過則成為店長
     * 不通過則刪除信息
     */
    public function change_shopowner_status(){
        $type = I('get.is_success');
        if($type == 1){
            $where['id'] = I('get.id');
            $data['is_shopowner'] = 1;

            $result = $this->serverModel->where($where)->save($data);

            if ($result > 0) {
                $this->tyAjaxReturn(1, '審核成功');
            } else {
                $this->tyAjaxReturn(0, '審核失敗');
            }
        }
        else if($type == 0){
            $where['id'] = I('get.id');

            $result = $this->serverModel->where($where)->delete();

            if ($result > 0) {
                $this->tyAjaxReturn(1, '審核成功');
            } else {
                $this->tyAjaxReturn(0, '審核失敗');
            }
        }
    }
    public function staff_list(){
        $where['p_id'] = '-1';
        $where['is_staff'] = '1';
        $serverList = $this->serverModel->where($where)->order('id desc')->select();
        foreach($serverList as$key => $val){
            if(isset($val['server_address_id'])){
                $serverAddressArr = explode(',', $val['server_address_id']);
                foreach($serverAddressArr as $k => $v){
                    $serverList[$key]['server_address'][$v] = $this->serverAddressModel->where('id = '.$v)->find();
                }
            }
        }
//         p($serverList);
        $serverAddressList = $this->serverAddressModel->select();
        $this->assign('salist',$serverAddressList);
        $this->assign('list',$serverList);
        $this->display();
    }

    public function edit_staff_info(){
        $where['id'] = I('post.staff_id');
        $data['server_address_id'] = substr(I('post.server_address_id'),0,strlen(I('post.server_address_id'))-1);
        $result = $this->serverModel->where($where)->save($data);
        if($result){
            $returndata['status'] = 1;
            $returndata['info'] = '設置成功！';
            $returndata['url'] = U(MODULE_NAME.'/Audit/staff_list');
            $this->ajaxReturn($returndata);
        }else{
            $returndata['status'] = 0;
            $returndata['info'] = '設置失敗！';
            $this->ajaxReturn($returndata);
        }
    }

    public function delete_staff(){
        $where['id'] = I('get.id');
        $deleteResult = $this->serverModel->where($where)->delete();
        if($deleteResult){
            $returndata['status'] = 1;
            $returndata['info'] = '刪除成功！';
            $this->ajaxReturn($returndata);
        }else{
            $returndata['status'] = 0;
            $returndata['info'] = '刪除失敗！';
            $this->ajaxReturn($returndata);
        }
    }

    /**
     * 店长列表
     */
    public function server_list(){
        $where['p_id'] = '0';
        $serverList = $this->serverModel->where($where)->order('id desc')->select();

        $this->assign('list',$serverList);
        $this->display();
    }

    /**
     * 店长信息
     */
    public function server_info(){
        $where['id'] = I('get.id');

        $serverInfo = $this->serverModel->where($where)->find();

        if($serverInfo['shop_img'] == ''){
            $serverInfo['shop_img'] = $serverInfo['weixin_avatar'];
        }

        $serverAddress = D('serverAddress')->where('server_id = '.$serverInfo['id'])->select();
        if($serverAddress){
            $this->assign('address',$serverAddress);
        }else{
            $this->assign('address','no');
        }

        $this->assign('info',$serverInfo);
        $this->display('edit_server');
    }

    /**
     * 保存店長信息
     */
    public function save_new_shop_info(){
        $where['id'] = $serverWhere['server_id'] = I('post.server_id');
        $data['name'] = I('post.name');
        $data['phone'] = I('post.phone');
        $data['address'] = I('post.address');
        $data['tips'] = I('post.tips');

        $getResult = $this->address_analysis($data);
        $geocode = explode(',', $getResult['geocodes'][0]['location']);

        $data['lon'] = $geocode[0];
        $data['lat'] = $geocode[1];
        //判斷是否有上傳圖片
        if($_FILES['upload_shopImg']['name']){
            $config = array(
                'maxSize' => 0, //上传的文件大小限制 (0-不做限制)
                'exts' => array('jpg', 'gif', 'png', 'jpeg'),// 设置附件上传类型
                'subName' => array('date', 'Ymd'), //子目录创建方式，[0]-函数名，[1]-参数，多个参数使用数组
                'saveName'   =>    array('uniqid',''),
                'savePath' => 'server_img/', //保存路径
                'rootPath' => './Upload/',
                'autoSub'    =>    true,
            );
            $this->uploader = new Upload($config, 'Local');
            $info = $this->uploader->upload($_FILES);
            if(!$info){//提示错误信息
                $returndata ['status'] = 0; // 状态
                $returndata ['info'] = $this->uploader->getError();
                $this->ajaxReturn($returndata);
            }else{
                foreach($info as$x =>$val){
                    $data['shop_img'] = '/upload/'.$val['savepath'] . $val['savename'];
                }
            }
        }
        //保存基礎信息
        $updateserver = $this->serverModel->where($where)->save($data);
        //保存地址信息
        $addressData = I('post.address_name');
        //删除原有地址
        $checkWhere['server_id'] = $serverWhere['server_id'];
        $checkResult = $this->serverAddressModel->where($checkWhere)->delete();
        //在保存新地址
        foreach($addressData as$k => $v){
            $analysisData['address'] = $v;
            $analysisResult = $this->address_analysis($analysisData);
            $analysis = explode(',', $analysisResult['geocodes'][0]['location']);

            $addNewAddress['lon'] = $analysis[0];
            $addNewAddress['lat'] = $analysis[1];
            $addNewAddress['address_name'] = $v;
            $addNewAddress['server_id'] = $serverWhere['server_id'];
            $this->serverAddressModel->add($addNewAddress);
        }

        if($updateserver!==false){
            $returndata['status'] = 1;
            $returndata['info'] = '上傳成功！';
            $this->ajaxReturn($returndata);
        }else{
            $returndata['status'] = 0;
            $returndata['info'] = '上傳失敗！';
            $this->ajaxReturn($returndata);
        }
    }

    public function delete_address(){
        $where['id'] = I('post.addressId');
        $deleteResult = $this->serverAddressModel->where($where)->delete();
        if($deleteResult){
            $returndata['status'] = 1;
            $returndata['info'] = '刪除成功！';
            $this->ajaxReturn($returndata);
        }else{
            $returndata['status'] = 0;
            $returndata['info'] = '刪除失敗！';
            $this->ajaxReturn($returndata);
        }
    }

    public function audit_staff_list(){
        $checkJoinWhere['p_id'] = -1;
        $checkJoinWhere['is_staff'] = 0;
        $waitJoinList = $this->serverModel->where($checkJoinWhere)->select();
        $this->assign('list',$waitJoinList);
        $this->display();
    }

    /**
     * 修改店長審核狀態
     * 通過則成為店長
     * 不通過則刪除信息
     */
    public function change_staff_status(){
        $type = I('get.is_success');
        if($type == 1){
            $where['id'] = I('get.id');
            $data['is_staff'] = 1;

            $result = $this->serverModel->where($where)->save($data);

            if ($result > 0) {
                $this->tyAjaxReturn(1, '審核成功');
            } else {
                $this->tyAjaxReturn(0, '審核失敗');
            }
        }
        else if($type == 0){
            $where['id'] = I('get.id');

            $result = $this->serverModel->where($where)->delete();

            if ($result > 0) {
                $this->tyAjaxReturn(1, '審核成功');
            } else {
                $this->tyAjaxReturn(0, '審核失敗');
            }
        }
    }

    /**
     * 解析地址轉換成經緯度
     */
    public function address_analysis($data){
        //地理編碼把地址轉換成經緯度
        $getData = 'http://restapi.amap.com/v3/geocode/geo?key=9cd137305f879d522cc8049535fb196d&address='.$data['address'];
        $getResultJson = file_get_contents($getData);
        $getResult = json_decode($getResultJson,true);

        return $getResult;
    }

    public function admin_password_change(){
        if(IS_GET){
            $this->display();
        }
        if(IS_POST){
            $checkWhere['server_id'] = $where['server_id'] = -1;
            $checkWhere['admin_password'] = md5(I('post.old_pwd'));

            $checkResult = $this->serverAdminModel->where($checkWhere)->find();
            if(!$checkResult){
                $returndata['status'] = 0;
                $returndata['info'] = '原密碼不正確！';
                $this->ajaxReturn($returndata);
            }
            if(I('post.new_pwd') != I('post.confirm_new_pwd')){
                $returndata['status'] = 0;
                $returndata['info'] = '新密碼與確認密碼不一致！';
                $this->ajaxReturn($returndata);
            }

            $data['admin_password'] = md5(I('post.new_pwd'));
            $result = $this->serverAdminModel->where($where)->save($data);
            if($result){
                //清空session数据
                $_SESSION = array();

                //删除客户端cookie中保存的sessionid
                if (isset($_COOKIE[session_name()])) {
                    setcookie(session_name(), '', time() - 3600, C('COOKIE_PATH'));
                }

                //彻底销毁session
                session_destroy();

                S('menuList', NULL);
                S('allMenuId', NULL);
                S('language', NULL);
                S('currency', NULL);
                S('oauths', NULL);
                S('sysConfig', NULL);
                S('jsCacheNum', NULL);
                S('categoryList',NULL);


                $returndata['status'] = 1;
                $returndata['info'] = '修改成功！請重新登錄';
                $returndata['url'] = U(MODULE_NAME . "/Public/login", '', true, false, true, true);
                $this->ajaxReturn($returndata);
            }else{
                $returndata['status'] = 0;
                $returndata['info'] = '修改失敗！';
                $this->ajaxReturn($returndata);
            }
        }
    }

    public function month_car_list(){
        $this->display();
    }
}
